﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DrugStore.Models;
using System.Web.Mvc;
using DrugStore.Helper;

namespace DrugStore.Controllers
{
    public class ManageNewsController : Controller
    {
        //
        // GET: /ManageNews/
        [MyAuthorize(LoginPage="/Admin/Logon")]
        public ActionResult Index(int pageIndex=1,string message="",string keyword = "",string field="",string orderField="",string direction="")
        {           
            ViewData["message"] = message;
            int pageSize = 20;
            ManageNewBusiness business = new ManageNewBusiness();
            PaginateList<News> listNews = business.Search(keyword, field, pageIndex, pageSize, orderField, direction);
            return View(listNews);                                    
        }

        [MyAuthorize(LoginPage = "/Admin/LogOn")]
        public ActionResult Add() 
        {
            try
            {
                ManageNewBusiness business = new ManageNewBusiness();
                NewCategoryBusiness caBusiness = new NewCategoryBusiness();
                ManageNewModel model = new ManageNewModel();
                //Guid id = caBusiness.SelectCategoryId();
                NewCategoryBusiness ncBusiness = new NewCategoryBusiness();
                List<Category> categories = ncBusiness.SelectCategories();
                if (categories == null)
                    model.Categories = new List<Category>();
                else model.Categories = ncBusiness.SelectCategories();
                model.SelectedCategories = new List<string>();
                return View(model);
            }
            catch (Exception ex) 
            {
                ViewData["message"] = ex.Message;
            }
            return View();
        }

        
        [ValidateInput(false)]
        [MyAuthorize(LoginPage="/Admin/Logon")]
        [HttpPost]
        public ActionResult Add(ManageNewModel model, HttpPostedFileBase imgPath) 
        {
            try 
            {
                NewCategoryBusiness caBusiness = new NewCategoryBusiness();
                NewBussiness business = new NewBussiness();
                NewCategoryBusiness ncBusiness = new NewCategoryBusiness();
                List<Category> categories = ncBusiness.SelectCategories();
                if (categories == null)
                    model.Categories = new List<Category>();
                else model.Categories = categories;

                if (model.SelectedCategories == null)
                {
                    model.SelectedCategories = new List<string>();
                    //throw new Exception("Nếu bạn không chọn danh mục, website sẽ không thể tự động hiển thị tin này");
                }

                if (ModelState.IsValid) 
                {
                    if (imgPath == null) 
                    {
                        throw new Exception("Bạn chưa tạo ảnh đại diện");
                    }
                    String image = Guid.NewGuid().ToString();
                    String ext = imgPath.FileName.Substring(imgPath.FileName.LastIndexOf("."));
                    String path = HttpContext.Server.MapPath("/Content/newImages/"+image+ext);
                    imgPath.SaveAs(path);
                    model.ImagePath = "/Content/newImages/" + image + ext;
                    business.AddNews(model);
                    ViewData["message"] = "Thêm tin mới thành công";
                    return RedirectToAction("Index","ManageNews");
                }
            }
            catch (Exception ex) 
            {
                ModelState.AddModelError("",ex.Message);
            }
            return View(model);
        }

        [MyAuthorize(LoginPage = "/Admin/Logon")]        
        public ActionResult Edit(String id) 
        {
            try
            {
                ManageNewBusiness business = new ManageNewBusiness();
                ManageNewModel news = business.GetNewsById(id);
                return View(news);
            }
            catch (Exception ex) 
            {
                ViewData["message"] = ex.Message;
            }
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        [MyAuthorize(LoginPage = "/Admin/Logon")]
        public ActionResult Edit(String id, ManageNewModel model, HttpPostedFileBase imgPath) 
        {
            try
            {
                NewBussiness business = new NewBussiness();

                //Get all News Categories
                NewCategoryBusiness ncBusiness = new NewCategoryBusiness();
                List<Category> categories = ncBusiness.SelectCategories();
                model.NewsId = id;
                if (categories == null)
                    model.Categories = new List<Category>();
                else model.Categories = categories;

                if (model.SelectedCategories == null)
                {
                    model.SelectedCategories = new List<string>();
                }
                //end

                if (ModelState.IsValid) 
                {
                    if (imgPath != null)
                   {
                       String name = Guid.NewGuid().ToString();
                       String ext = imgPath.FileName.Substring(imgPath.FileName.LastIndexOf("."));
                       String path = HttpContext.Server.MapPath("/Content/newImages/" + name + ext);
                       imgPath.SaveAs(path);
                       model.ImagePath = "/Content/newImages/" + name + ext;
                   }

                   business.UpdateNews(model);
                   return RedirectToAction("Index", "ManageNews");
                   }
            }
            catch (Exception ex) 
            {
                ViewData["message"] = ex.Message;
            }
            return View(model);
        }

        [MyAuthorize(LoginPage = "/Admin/Logon")]     
        public ActionResult Delete(String id) 
        {
            try
            {
                NewBussiness business = new NewBussiness();
                business.Delete(id);
                return RedirectToAction("Index");
            }
            catch (Exception ex) 
            {
                return RedirectToAction("Index", new { message = ex.Message });
            }
        }

        [MyAuthorize(LoginPage = "/Admin/Logon")]
        public ActionResult AddCategory()
        {
            ManageNewBusiness business = new ManageNewBusiness();
            NewsCategoryModel model = business.GetNewsCategoryModel(null);
            return View(model);
        }

        [MyAuthorize(LoginPage = "/Admin/Logon")]
        [HttpPost]
        public ActionResult AddCategory(NewsCategoryModel model)
        {
            ManageNewBusiness business = new ManageNewBusiness();
            try
            {
                if (ModelState.IsValid)
                {
                    business.AddCategoty(model);
                    return RedirectToAction("AddCategory");
                }
            }
            catch (Exception ex)
            {
                ViewData["message"] = ex.Message;
            }
            model.Categories = business.GetAllCategory();
            return View(model);
        }

        [MyAuthorize(LoginPage = "/Admin/Logon")]
        public ActionResult EditCategory(String id)
        {
            ManageNewBusiness business = new ManageNewBusiness();
            NewsCategoryModel model = business.GetNewsCategoryModel(id);
            return View(model);
        }

        [MyAuthorize(LoginPage = "/Admin/Logon")]
        [HttpPost]
        public ActionResult EditCategory(String id, NewsCategoryModel model)
        {
            ManageNewBusiness business = new ManageNewBusiness();
            try
            {
                model.CategoryId = id;
                if (ModelState.IsValid)
                {
                    business.UpdateCategory(model);
                    return RedirectToAction("AddCategory");
                }
            }
            catch (Exception ex)
            {
                ViewData["message"] = ex.Message;
            }
            model.Categories = business.GetAllCategory();
            return View(model);
        }

        [MyAuthorize(LoginPage = "/Admin/Logon")]
        public ActionResult DeleteCategory(String id)
        {
            ManageNewBusiness business = new ManageNewBusiness();
            try
            {
                business.DeleteCategoty(id);
            }
            catch (Exception ex)
            {

            }
            return RedirectToAction("AddCategory");
        }
    }
}
